package com.cvr.project.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.cvr.project.R;
import com.cvr.project.api.ApiService;
import com.cvr.project.repertory.LViewModelProviders;
import com.cvr.project.utils.ToastUtils;
import com.cvr.project.utils.WatermarkManager;
import com.cvr.project.viewmodel.MainViewModel;
import com.gyf.immersionbar.ImmersionBar;
import com.huashi.otg.sdk.HSIDCardInfo;
import com.huashi.otg.sdk.HSLOG;
import com.huashi.otg.sdk.HandlerMsg;
import com.huashi.otg.sdk.HsOtgApi;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Objects;

public class IDCardActivity extends AppCompatActivity {

    private TextView tv_info, statu, tv_Log;
    private ImageView iv_photo;
    private Button conn, read, autoread;

    boolean m_Con = false;

    boolean m_Auto = false;
    long startTime;
    HsOtgApi api = null;
    String filepath = "";
    SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");// 设置日期格式
    int m_ReadIDCardSUCCESS = 0;
    private MainViewModel viewModel;
    @SuppressLint("HandlerLeak")
    Handler h = new Handler() {
        @SuppressLint({"DefaultLocale", "SetTextI18n"})
        public void handleMessage(Message msg) {
            if (msg.what == 99 || msg.what == 100) {
                statu.setText((String) msg.obj);
                m_Con = false;
            }
            // 第一次授权时候的判断是利用handler判断，授权过后就不用这个判断了
            if (msg.what == HandlerMsg.CONNECT_SUCCESS) {
                statu.setText("连接成功" + api.GetSAMID());
                m_Con = true;
                //sam.setText(api.GetSAMID());
            }
            if (msg.what == HandlerMsg.CONNECT_ERROR) {
                statu.setText("连接失败");
            }
            if (msg.what == HandlerMsg.READ_ERROR) {
                // cz();
                // statu.setText("卡认证失败");
                statu.setText("请放卡...");
            }
            if (msg.what == HandlerMsg.READ_SUCCESS) {

                HSIDCardInfo ic = (HSIDCardInfo) msg.obj;
                byte[] fp = new byte[1024];
                fp = ic.getFpDate();
                String m_FristPFInfo = "";
                String m_SecondPFInfo = "";

                if (fp[4] == (byte) 0x01) {
                    m_FristPFInfo = String.format(
                            "指纹  信息：第一枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[5]), fp[6]);
                } else {
                    m_FristPFInfo = "身份证无指纹 \n";
                }
                if (fp[512 + 4] == (byte) 0x01) {
                    m_SecondPFInfo = String.format(
                            "指纹  信息：第二枚指纹注册成功。指位：%s。指纹质量：%d \n",
                            GetFPcode(fp[512 + 5]), fp[512 + 6]);
                } else {
                    m_SecondPFInfo = "身份证无指纹 \n";
                }
                if (ic.getcertType() == " ") {
                    tv_info.setText("证件类型：身份证\n" + "姓名：" + ic.getPeopleName()
                            + "\n" + "性别：" + ic.getSex() + "\n" + "民族："
                            + ic.getPeople() + "\n" + "出生日期："
                            + df.format(ic.getBirthDay()) + "\n" + "地址："
                            + ic.getAddr() + "\n" + "身份号码：" + ic.getIDCard()
                            + "\n" + "签发机关：" + ic.getDepartment() + "\n"
                            + "有效期限：" + ic.getStrartDate() + "-"
                            + ic.getEndDate() + "\n" + m_FristPFInfo + "\n"
                            + m_SecondPFInfo);
                } else {
                    if (ic.getcertType() == "J") {
                        tv_info.setText("证件类型：港澳台居住证（J）\n" + "姓名："
                                + ic.getPeopleName() + "\n" + "性别："
                                + ic.getSex() + "\n" + "签发次数："
                                + ic.getissuesNum() + "\n" + "通行证号码："
                                + ic.getPassCheckID() + "\n" + "出生日期："
                                + df.format(ic.getBirthDay()) + "\n" + "地址："
                                + ic.getAddr() + "\n" + "身份号码："
                                + ic.getIDCard() + "\n" + "签发机关："
                                + ic.getDepartment() + "\n" + "有效期限："
                                + ic.getStrartDate() + "-" + ic.getEndDate()
                                + "\n" + m_FristPFInfo + "\n" + m_SecondPFInfo);
                    } else {
                        if (ic.getcertType() == "I") {
                            tv_info.setText("证件类型：外国人永久居留证（I）\n" + "英文名称："
                                    + ic.getPeopleName() + "\n" + "中文名称："
                                    + ic.getstrChineseName() + "\n" + "性别："
                                    + ic.getSex() + "\n" + "永久居留证号："
                                    + ic.getIDCard() + "\n" + "国籍："
                                    + ic.getstrNationCode() + "\n" + "出生日期："
                                    + df.format(ic.getBirthDay()) + "\n"
                                    + "证件版本号：" + ic.getstrCertVer() + "\n"
                                    + "申请受理机关：" + ic.getDepartment() + "\n"
                                    + "有效期限：" + ic.getStrartDate() + "-"
                                    + ic.getEndDate() + "\n" + m_FristPFInfo
                                    + "\n" + m_SecondPFInfo);
                        } else {
                            if (ic.getcertType() == "Y") {
                                tv_info.setText("证件类型：外国人永久居留证（Y）\n" + "英文名称："
                                        + ic.getPeopleName() + ic.getStandbyEName() + "\n" + "中文名称："
                                        + ic.getstrChineseName() + "\n" + "性别："
                                        + ic.getSex() + "\n" + "永久居留证号："
                                        + ic.getIDCard() + "\n" + "国籍："
                                        + ic.getstrNationCode() + "\n" + "出生日期："
                                        + df.format(ic.getBirthDay()) + "\n"
                                        + "签发次数：" + ic.getissuesNum() + "\n"
                                        + "旧版ID号：" + ic.getOldIDCardNumber() + "\n"
                                        + "有效期限：" + ic.getStrartDate() + "-"
                                        + ic.getEndDate() + "\n" + m_FristPFInfo
                                        + "\n" + m_SecondPFInfo);
                            }
                        }
                    }

                }
                try {
                    byte[] bmpBuf = new byte[102 * 126 * 3 + 54 + 126 * 2]; // 照片头像bmp数据
                    String bmpPath = filepath + "/zp.bmp"; // 照片头像保存路径
                    int ret = api.unpack(ic.getwltdata(), bmpBuf, "");
                    if (ret != 1) {// 解码失败
                        statu.setText("头像解码失败");
                        return;
                    }

                    Bitmap bitmap = BitmapFactory.decodeByteArray(bmpBuf, 0,
                            bmpBuf.length);
                    iv_photo.setImageBitmap(bitmap); // 显示头像
                    //////////////////////////////////////////////////////////////////////////////////////
                    // 生成证件正反面，需要给filepath授权写权限
                  /* try {
                       // GetImg.ShowBmp(ic, MainActivity.this, 1, filepath,bitmap);
                        iv_photo.setImageBitmap(GetImg.ShowBmp(ic, MainActivity.this, 1, filepath,bitmap)); // 显示正反面
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }*/
                    //////////////////////////////////////////////////////////////////////////////////////
                    if (!m_Auto) {
                        startTime = System.currentTimeMillis() - startTime;
                        statu.setText("读卡成功,用时：" + startTime);
                        showLoading();
                        viewModel.icCardLogin(Objects.equals(ic.getcertType(), "J") ? ic.getissuesNum() : ic.getIDCard(), HomeActivity.phone);
                    } else {
                        statu.setText("读卡成功");
                        m_ReadIDCardSUCCESS++;
                        tv_Log.setText("成功次数:" + m_ReadIDCardSUCCESS);
                        showLoading();
                        viewModel.icCardLogin(Objects.equals(ic.getcertType(), "J") ? ic.getissuesNum() : ic.getIDCard(), HomeActivity.phone);
                    }
                } catch (Exception e) {
                    ToastUtils.showToast(getApplicationContext(), "头像解码失败");
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImmersionBar.with(this).transparentStatusBar().titleBar(R.id.app_title).navigationBarColor(R.color.white).statusBarDarkFont(true).init();
        

        
        filepath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/wltlib";// 授权目录
        Log.e("LJFDJ", filepath);
        isFolderExists(filepath);
        initView();
        setEnven();
        onPostHttpEvent();
        // 高版本安卓需要自动申请SD卡读写权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (IDCardActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    IDCardActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                }
            }
        }

        // android 12
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        } else {
            // Permission has already been granted, read the file

        }
    }

    private void onPostHttpEvent() {
        viewModel = LViewModelProviders.of(this, MainViewModel.class);
        viewModel.icCardLoginLiveData.observe(this, idCardEntity -> {
            onDismissProgress();
            WebViewActivity.getInstance(IDCardActivity.this,  idCardEntity.getToken_info().getToken());
            finish();
        });
        viewModel.errorTipLiveData.observe(this, s -> {
            onDismissProgress();
            ToastUtils.showToast(IDCardActivity.this, s);
        });
    }
    private ProgressDialog progressDialog;

    private void showLoading() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("上传中，请稍等...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    private void onDismissProgress() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    private void setEnven() {
        conn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (m_Con) {
                    m_Auto = false;
                    SystemClock.sleep(1500);
                    if (api != null) {
                        api.unInit();
                        api = null;
                    }
                    m_Con = false;
                    statu.setText("断开连接成功");
                    conn.setText("连接");
                } else {
                    if (api == null) {
                        api = new HsOtgApi(h, IDCardActivity.this);
                    }
                    int ret = api.init();// 因为第一次需要点击授权，第一次点击时候的返回是-1,我利用了广播接受到授权后用handler发送消息
                    HSLOG.m_Addlog = false;
                    if (ret == 1) {
                        statu.setText("连接成功,模块号：" + api.GetSAMID());
                        m_Con = true;
                        conn.setText("断开");
                    } else {
                        statu.setText("连接失败");
                        m_Con = false;
                    }
                }
            }
        });
        read.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!m_Con) {
                    statu.setText("100U未连接");
                    return;
                }
                cz();
                startTime = System.currentTimeMillis();
                if (api.Authenticate(200, 200) != 1) {
                    statu.setText("卡认证失败");
                    return;
                }
                HSIDCardInfo ici = new HSIDCardInfo();
                if (api.ReadCard(ici, 200, 1300) == 1) {
                    Message msg = Message.obtain();
                    msg.obj = ici;
                    msg.what = HandlerMsg.READ_SUCCESS;
                    h.sendMessage(msg);
                }
            }

        });
        autoread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (!m_Con) {
                    statu.setText("100U未连接");
                    return;
                }
                cz();
                if (m_Auto) {
                    m_Auto = false;
                    autoread.setText("自动读卡");
                } else {
                    m_Auto = true;
                    new Thread(new CPUThread()).start();
                    m_ReadIDCardSUCCESS = 0;
                    autoread.setText("停止读卡");
                }
            }
        });

    }

    private void cz() {
        tv_info.setText("");
        iv_photo.setImageBitmap(null);
        tv_Log.setText("");
    }

    public class CPUThread extends Thread {
        public CPUThread() {
            super();
        }

        @Override
        public void run() {
            super.run();
            HSIDCardInfo ici;
            Message msg;
            while (m_Auto) {
                // ///////////////循环读卡，不拿开身份证
                // if (api.NotAuthenticate(200, 200) == 1) {
                // ////////////////循环读卡，需要重新拿开身份证
                if (api.Authenticate(200, 200) == 1) {
                    ici = new HSIDCardInfo();
                    if (api.ReadCard(ici, 200, 1300) == 1) {
                        msg = Message.obtain();
                        msg.obj = ici;
                        msg.what = HandlerMsg.READ_SUCCESS;
                        h.sendMessage(msg);
                    } else {
                        // 读卡失败
                        msg = Message.obtain();
                        msg.what = HandlerMsg.READ_ERROR;
                        h.sendMessage(msg);
                        SystemClock.sleep(300);
                    }
                } else {
                    // 卡认证失败
                    msg = Message.obtain();
                    msg.what = HandlerMsg.READ_ERROR;
                    h.sendMessage(msg);
                    SystemClock.sleep(300);
                }
            }
        }
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        tv_info = findViewById(R.id.tv_info);
        statu = findViewById(R.id.statu);
        iv_photo = findViewById(R.id.iv_photo);
        conn = findViewById(R.id.conn);
        read = findViewById(R.id.read);
        autoread = findViewById(R.id.autoread);
        tv_Log = findViewById(R.id.tv_Log);
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("身份识别");
    }

    @Override
    protected void onDestroy() {
        // 移除水印
        WatermarkManager.getInstance().removeWatermark(this);
        
        super.onDestroy();
        onDismissProgress();
        if (m_Auto) {
            m_Auto = false;
            SystemClock.sleep(1500);
        }
        if (api == null) {
            return;
        }
        api.unInit();
    }

    /**
     * 指纹 指位代码
     *
     * @param FPcode
     * @return
     */
    String GetFPcode(int FPcode) {
        switch (FPcode) {
            case 11:
                return "右手拇指";
            case 12:
                return "右手食指";
            case 13:
                return "右手中指";
            case 14:
                return "右手环指";
            case 15:
                return "右手小指";
            case 16:
                return "左手拇指";
            case 17:
                return "左手食指";
            case 18:
                return "左手中指";
            case 19:
                return "左手环指";
            case 20:
                return "左手小指";
            case 97:
                return "右手不确定指位";
            case 98:
                return "左手不确定指位";
            case 99:
                return "其他不确定指位";
            default:
                return "未知";
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        
        // 添加水印
        WatermarkManager.getInstance().addWatermark(this);
    }
    

    
    boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        if (!file.exists()) {
            if (file.mkdir()) {
                return true;
            } else
                return false;
        }
        return true;
    }
}
